import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { API_CODE, API_CONFIG, CONTENT_TYPE, HTTP_STATUS, STORAGE_KEYS } from '../constants/common';
import { navigateToLogin } from '../utils/navigation';
import { handleApiError } from '../utils/errorManager';

/**
 * API响应接口
 */
export interface ApiResponse<T = any> {
  code: number;
  message?: string;  // 前端格式
  msg?: string;      // 后端格式
  data: T;
  timestamp?: number;
}

/**
 * 分页响应接口
 */
export interface PageResponse<T = any> {
  records: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
}

/**
 * 创建axios实例
 */
const api: AxiosInstance = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': CONTENT_TYPE.JSON,
  },
});

/**
 * 请求拦截器
 */
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
    
    // 开发环境下打印token调试信息（屏蔽OPTIONS请求）
    if (import.meta.env.MODE === 'development' && config.method?.toUpperCase() !== 'OPTIONS') {
      console.log('[API Request Debug]', {
        url: config.url,
        method: config.method,
        hasToken: !!token,
        tokenPreview: token ? `${token.substring(0, 20)}...` : 'No token',
      });
    }
    
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 添加租户信息
    const tenant = localStorage.getItem(STORAGE_KEYS.TENANT);
    if (tenant && config.headers) {
      try {
        const tenantData = JSON.parse(tenant);
        config.headers['X-Tenant-ID'] = tenantData.id;
      } catch (e) {
        console.warn('Failed to parse tenant data:', e);
      }
    }
    
    return config;
  },
  (error) => {
    console.error('Request interceptor error:', error);
    return Promise.reject(error);
  }
);

/**
 * 响应拦截器
 */
api.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    // 屏蔽OPTIONS预检请求的提示与业务解析
    if (response.config?.method?.toUpperCase() === 'OPTIONS') {
      return response.data;
    }
    const { data } = response;
    
    // 请求成功
    if (data.code === 0) {
      return data.data;
    }
    
    // 业务错误 - 后端使用msg字段而非message字段
    const errorMessage = data.msg || data.message || '请求失败';
    handleApiError.business(errorMessage, data.code);
    // 标记为已由拦截器处理的业务错误，避免在错误分支再次提示
    return Promise.reject({ __handledByInterceptor: true, errorType: 'business', message: errorMessage, code: data.code });
  },
  (error) => {
    console.error('Response interceptor error:', error);
    // 屏蔽OPTIONS预检请求的错误提示
    if (error?.config?.method?.toUpperCase() === 'OPTIONS') {
      return Promise.reject({ __silent: true, reason: 'options_preflight', original: error });
    }
    // 如果是业务错误（已由上面的成功分支处理过提示），不再重复提示
    if (error && error.__handledByInterceptor) {
      return Promise.reject(error);
    }
    
    // 网络错误或HTTP状态码错误
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case HTTP_STATUS.UNAUTHORIZED:
          handleApiError.unauthorized();
          // 清除本地存储
          localStorage.removeItem(STORAGE_KEYS.TOKEN);
          localStorage.removeItem(STORAGE_KEYS.USER);
          localStorage.removeItem(STORAGE_KEYS.TENANT);
          // 自动跳转到登录页
          navigateToLogin();
          break;
          
        case HTTP_STATUS.FORBIDDEN:
          handleApiError.forbidden();
          break;
          
        case HTTP_STATUS.NOT_FOUND:
          handleApiError.notFound();
          break;
          
        case HTTP_STATUS.INTERNAL_SERVER_ERROR:
          handleApiError.serverError();
          break;
          
        default:
          const errorMessage = data?.msg || data?.message || `请求失败 (${status})`;
          handleApiError.httpStatus(status, errorMessage, error.config?.url);
      }
    } else if (error.request) {
      handleApiError.network();
    } else {
      handleApiError.business('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

/**
 * 创建平台管理API实例
 */
export const platformApi: AxiosInstance = axios.create({
  baseURL: API_CONFIG.SYSTEM_SERVICE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': CONTENT_TYPE.JSON,
  },
});

/**
 * 平台API请求拦截器
 */
platformApi.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加平台认证token
    const token = localStorage.getItem(STORAGE_KEYS.PLATFORM_TOKEN);
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 添加租户信息（如果需要）
    const tenant = localStorage.getItem(STORAGE_KEYS.TENANT);
    if (tenant && config.headers) {
      try {
        const tenantData = JSON.parse(tenant);
        config.headers['X-Tenant-ID'] = tenantData.id;
      } catch (e) {
        console.warn('Failed to parse tenant data:', e);
      }
    }
    
    // 日志屏蔽OPTIONS请求）
    if (config.method?.toUpperCase() !== 'OPTIONS') {
      console.log(`[Platform API] ${config.method?.toUpperCase()} ${config.url}`, {
        baseURL: config.baseURL,
        headers: config.headers,
      });
    }
    
    return config;
  },
  (error) => {
    console.error('Platform API request error:', error);
    return Promise.reject(error);
  }
);

/**
 * 平台API响应拦截器
 */
platformApi.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    // 屏蔽OPTIONS预检请求的提示与业务解析
    if (response.config?.method?.toUpperCase() === 'OPTIONS') {
      return response.data;
    }
    const { data } = response;
    if (data.code === API_CODE.SUCCESS) {
      return data.data;
    }
    // 后端使用msg字段而非message字段
    const errorMessage = data.msg || data.message || '请求失败';
    handleApiError.business(errorMessage, data.code);
    // 标记为已由拦截器处理的业务错误，避免在错误分支再次提示
    return Promise.reject({ __handledByInterceptor: true, errorType: 'business', message: errorMessage, code: data.code });
  },
  (error) => {
    console.error('Platform API response error:', error);
    // 屏蔽OPTIONS预检请求的错误提示
    if (error?.config?.method?.toUpperCase() === 'OPTIONS') {
      return Promise.reject({ __silent: true, reason: 'options_preflight', original: error });
    }
    // 如果是业务错误（已由上面的成功分支处理过提示），不再重复提示
    if (error && error.__handledByInterceptor) {
      return Promise.reject(error);
    }
    
    if (error.response?.status === HTTP_STATUS.UNAUTHORIZED) {
      // 检查是否为租户登录请求，如果是则不重定向到platform-login
      const requestUrl = error.config?.url || '';
      const isTenantLogin = requestUrl.includes('/api/v3/tenant/auth/login');
      
      if (!isTenantLogin) {
        handleApiError.unauthorized('平台认证失效，请重新登录');
        localStorage.removeItem(STORAGE_KEYS.PLATFORM_TOKEN);
        localStorage.removeItem(STORAGE_KEYS.PLATFORM_USER);
        // 自动跳转到平台登录页
        navigateToLogin();
      }
    } else if (error.response) {
      // 其他HTTP错误
      const { status, data } = error.response;
      const errorMessage = data?.msg || data?.message;
      handleApiError.httpStatus(status, errorMessage, error.config?.url);
    } else if (error.request) {
      handleApiError.network();
    } else {
      handleApiError.business('平台API请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

/**
 * API工具函数
 */
export const httpUtils = {
  /**
   * 构建查询参数
   */
  buildParams: (params: Record<string, any>) => {
    const filteredParams: Record<string, any> = {};
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
        filteredParams[key] = params[key];
      }
    });
    return filteredParams;
  },

  /**
   * 处理文件下载
   */
  downloadFile: (blob: Blob, filename: string) => {
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  },

  /**
   * 格式化文件大小
   */
  formatFileSize: (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  },

  /**
   * 获取错误消息
   */
  getErrorMessage: (error: any): string => {
    if (error.response?.data?.message) {
      return error.response.data.message;
    }
    if (error.message) {
      return error.message;
    }
    return '操作失败';
  }
};

export default api;